package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl  implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.将订单数据，存入orders表中
        //查询地址表，获取收货人信息
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
//查询用户表，获取下单人信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.slectUserById(userId);
//查询购物车表，获取订单明细信息(只查询自己名下的购物车)
        List<ShoppingCart> cartList = shoppingCarMapper.select(userId);
        if (cartList == null || cartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        }
        Orders orders = new Orders();
        //拷贝属性值
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //补充缺少的属性值
        orders.setNumber(System.currentTimeMillis() + "");                        //订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);                        //订单状态
        orders.setUserId(BaseContext.getCurrentId());                        //userId
        orders.setOrderTime(LocalDateTime.now());                        //下单时间
        orders.setPayStatus(Orders.PAID);                        //支付状态
        orders.setPhone(addressBook.getPhone());                        //手机号phone
        orders.setAddress(addressBook.getDetail());                                                                //订单详细地址
        orders.setConsignee(addressBook.getConsignee());                          //收货人
        orders.setUserName(user.getName());  //下单人
        orderMapper.insert(orders);             //将信息插入到订单表中
        log.info("获取订单id", orders.getId());
        //2.将订单明细数据，存入到order_detail表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //循环遍历购物车表进行属性拷贝，构造订单明细
        cartList.forEach(Cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(Cart, orderDetail, "id");//ignoreProperties是将id排除在外了
            //关联id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        //批量插入订单明细信息
        orderDetailMapper.insertBeatch(orderDetailList);


        //3.清空购物车
        shoppingCarMapper.delete(userId);
        //4.构造OrderSubmitVO对象，并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.slectUserById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    @Override
    public PageResult selectHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setStatus(ordersPageQueryDTO.getStatus());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //分页条件查询
        Page<Orders> page = orderMapper.pageSelect(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList();
        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public void cancel(Long id) {

        // 1. 根据订单ID查询订单信息
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 2. 检查订单状态是否允许取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setId(orders.getId());
        // 3. 更新订单状态为已取消
        orders.setStatus(Orders.CANCELLED);
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    @Override
    public void insertX(Long id) {
        // 1. 根据订单ID查询订单信息
        Orders originalOrder = orderMapper.selectById(id);
        if (originalOrder == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 2. 查询原订单的订单明细
        List<OrderDetail> originalOrderDetails = orderDetailMapper.getByOrderId(originalOrder.getId());
        if (originalOrderDetails == null || originalOrderDetails.isEmpty()) {
            throw new OrderBusinessException("原订单没有订单明细");
        }

        // 3. 获取当前用户ID
        Long userId = BaseContext.getCurrentId();

        // 4. 将原订单的商品重新加入到当前用户的购物车中
        for (OrderDetail orderDetail : originalOrderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id", "orderId");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            //shoppingCart.s(LocalDateTime.now());
            shoppingCarMapper.insertBartch(shoppingCart);
        }
    }


//管理端


    @Override
    public PageResult selectPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 分页条件查询
        Page<Orders> page = orderMapper.pageSelect(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId(); // 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public void cancelOrders(String cancelReason, Long id) {
        // 1. 根据订单ID查询订单信息
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 2. 检查订单状态是否允许取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3. 如果订单已支付，需要进行退款


        // 4. 更新订单状态为已取消
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(cancelReason);
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public OrderVO details(Long id){   // 根据id查询订单

    Orders orders = orderMapper.selectById(id);

    // 查询该订单对应的菜品/套餐明细
    List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

    // 将该订单及其详情封装到OrderVO并返回
    OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
}

    @Override
    public OrderStatisticsVO statistics() {
        // 查询各个状态的订单数量

        Integer toBeConfirmedCount = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countByStatus(Orders.CONFIRMED);
        Integer deliveryInProgressCount = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        // 构造 OrderStatisticsVO 对象并返回
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .confirmed(confirmed)
                .toBeConfirmed(toBeConfirmedCount)
                .deliveryInProgress(deliveryInProgressCount)
                .build();
        return orderStatisticsVO;

    }
}
